package com.cetc;

import org.junit.Test;

import java.io.IOException;
import java.net.*;

/**
 * @Classname UDPTest
 * @Description UDP功能测试
 * @Date 2022/11/26 15:57
 * @Created by louzhuangxi
 */
public class UDPTest {
    @Test
    public void client() throws IOException {
        DatagramSocket socket = new DatagramSocket();
        //组装发送的数据包
        String data = "hello world";
        DatagramPacket packet = new DatagramPacket(data.getBytes(),0,data.length(), InetAddress.getLocalHost(),9000);
        socket.send(packet);
        socket.close();
    }

    @Test
    public void server() throws IOException {
        DatagramSocket socket = new DatagramSocket(9000);
        byte[] data = new byte[1024];
        DatagramPacket packet = new DatagramPacket(data, 0, data.length);
        socket.receive(packet);
        String str = new String(packet.getData(), 0, packet.getLength());
        System.out.println("收到的消息为:" + str);
        socket.close();
    }
}
